<script lang="ts" setup>
import { onUnmounted, ref } from 'vue'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '绑定手机',
    backgroundColor: '#FFFFFF',
    navigationBarTextStyle: 'black',
  },
})

// 判断是否已绑定手机（这里模拟已绑定状态）
const isBound = ref(false)
const currentPhone = ref('138****5678')

// 表单数据
const formData = ref({
  phone: '',
  verificationCode: '',
})

// 验证码倒计时
const countdown = ref(0)
const timer = ref<number | null>(null)

// 错误信息
const errorMessage = ref('')

// 启动验证码倒计时
function startCountdown() {
  countdown.value = 60
  timer.value = window.setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      if (timer.value)
        clearInterval(timer.value)
    }
  }, 1000)
}

// 发送验证码
function sendVerificationCode() {
  // 简单的手机号验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!formData.value.phone) {
    errorMessage.value = '请输入手机号码'
    return
  }
  if (!phoneRegex.test(formData.value.phone)) {
    errorMessage.value = '请输入正确的手机号码'
    return
  }

  // 清除错误信息
  errorMessage.value = ''

  // 模拟发送验证码
  console.log('发送验证码到:', formData.value.phone)

  uni.showToast({
    title: '验证码已发送',
    icon: 'success',
  })

  // 启动倒计时
  startCountdown()
}

// 提交绑定
function submitBind() {
  // 表单验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!formData.value.phone) {
    errorMessage.value = '请输入手机号码'
    return
  }
  if (!phoneRegex.test(formData.value.phone)) {
    errorMessage.value = '请输入正确的手机号码'
    return
  }
  if (!formData.value.verificationCode) {
    errorMessage.value = '请输入验证码'
    return
  }

  // 清除错误信息
  errorMessage.value = ''

  // 模拟API调用
  uni.showLoading({
    title: '处理中...',
  })

  setTimeout(() => {
    uni.hideLoading()

    // 模拟成功
    isBound.value = true
    currentPhone.value = formData.value.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')

    uni.showToast({
      title: '手机绑定成功',
      icon: 'success',
    })

    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }, 1000)
}

// 解绑手机
function unbindPhone() {
  uni.showModal({
    title: '解绑手机',
    content: '确定要解绑当前手机吗？解绑后将无法通过手机接收验证码。',
    success: (res) => {
      if (res.confirm) {
        // 模拟解绑操作
        uni.showLoading({
          title: '处理中...',
        })

        setTimeout(() => {
          uni.hideLoading()
          isBound.value = false
          currentPhone.value = ''

          uni.showToast({
            title: '手机解绑成功',
            icon: 'success',
          })
        }, 1000)
      }
    },
  })
}
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<template>
  <view class="bind-phone-container min-h-screen bg-slate-50 p-4">
    <!-- 已绑定状态 -->
    <view v-if="isBound" class="bound-status-container rounded-lg bg-white p-6 text-center">
      <view class="icon-container mb-4 text-4xl text-green-500">
        <i class="i-solar:smartphone-2-broken" />
      </view>
      <view class="mb-2 text-lg text-slate-900 font-medium">
        手机已绑定
      </view>
      <view class="mb-6 text-sm text-slate-500">
        当前绑定手机：{{ currentPhone }}
      </view>
      <button
        class="w-full border border-red-500 rounded-lg bg-white py-3 text-red-500"
        @click="unbindPhone"
      >
        解除绑定
      </button>
      <view class="mt-4 text-xs text-slate-400">
        解绑后需要重新绑定手机号以接收验证码和通知
      </view>
    </view>

    <!-- 未绑定状态，显示绑定表单 -->
    <view v-else class="bind-form-container rounded-lg bg-white p-4">
      <view class="form-item mb-5">
        <view class="label mb-1 text-sm text-slate-700">
          手机号码 *
        </view>
        <input
          v-model="formData.phone"
          type="tel"
          placeholder="请输入手机号码"
          :maxlength="11"
          class="w-full border border-slate-200 rounded-lg bg-white px-4 py-3 text-slate-900 focus:border-primary focus:outline-none"
        >
      </view>
      <view class="form-item mb-6">
        <view class="label mb-1 text-sm text-slate-700">
          验证码 *
        </view>
        <view class="flex space-x-3">
          <input
            v-model="formData.verificationCode"
            type="text"
            placeholder="请输入验证码"
            :maxlength="6"
            class="flex-1 border border-slate-200 rounded-lg bg-white px-4 py-3 text-slate-900 focus:border-primary focus:outline-none"
          >
          <button
            class="whitespace-nowrap rounded-lg px-4 py-2 text-sm"
            :class="countdown > 0 ? 'bg-slate-100 text-slate-400' : 'bg-slate-100 text-primary'"
            :disabled="countdown > 0"
            @click="sendVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}s后重新发送` : '获取验证码' }}
          </button>
        </view>
        <view class="error-message mb-6 text-xs text-red-500">
          {{ errorMessage }}
        </view>
        <button
          class="w-full rounded-lg bg-primary py-3 text-white"
          @click="submitBind"
        >
          确认绑定
        </button>
        <view class="mt-4 text-xs text-slate-400">
          绑定手机后，可以用于找回密码和接收重要通知
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.bind-phone-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
}

input {
  line-height: normal;
}

input::placeholder {
  color: #94a3b8;
}

button {
  line-height: normal;
}

button::after {
  border: none;
}

button:disabled {
  opacity: 0.6;
}

.form-item {
  transition: all 0.2s ease;
}

// 响应式调整
@media (min-width: 768px) {
  .bind-phone-container {
    max-width: 540px;
    margin: 0 auto;
  }
}
</style>
